#!/bin/bash

# Release - 20/03/09 #

############################ SupTime Project v0.6 ################################
# Hi, this is really-easy bash script which generates png image with your system #
# top and current uptime.                                                        #
##################################################################################
# Dear User - consider that this script has been written _FOR_PERSONAL_USE_.     #
# Please dont await anything amazing from it. Also my scripting knowledge is    #
# rather poor, so it is sure that there are many things in this script which     #
# could have been done much better...                                            #
##################################################################################
# Script requires:                                                               #
# - ImageMagick >= 6.2.5                                                         #
# - uptimed                                                                      #
# - uprecords (uprecords-cgi)                                                    #
# - ncftp                                                                        #
# - scp                                                                          #
##################################################################################
# Contact? >> sufixx[at]gmail.com                                                #
##################################################################################


# Configurable variables
BASE_DIR=`pwd` # better to put here normal path!
OUT=$BASE_DIR/out.png
THEME="theme_default"
#CHECKS=0	# Uncomment to disable software checks permamently

# Upload settings
UPLOAD="none"	# Choose method of image upload: ftp/scp/none
USER="user"
PASSWORD="password"
HOST="ftp.com"
FTP_PORT=21
SSH_PORT=22
FTP_DIR="public_html/"
SSH_DIR="~/"

# Binaries locations - Put here real binary locations
# You can search them with command: `whereis uprecords`
UPRECORDS_BIN=/usr/bin/uprecords
IDENTIFY_BIN=/usr/bin/identify
SCP_BIN=/usr/bin/scp
NCFTPPUT_BIN=/usr/bin/ncftpput
CONVERT_BIN=/usr/bin/convert
COMPOSITE_BIN=/usr/bin/composite

# No need to change
VERSION="0.6"
TMP_DIR=/tmp
BACKGROUND=$BASE_DIR/$THEME/bg.png
FOREGROUND=$BASE_DIR/$THEME/fg.png

# Script command-line parameters
case "$1" in
	-h)
		echo "[i] Available options are:"
		echo " -h	Show this help"
		echo " -i	Print information about settings"
		echo " -n	Turn off software checks"
		echo " -s	Generate shutdown image"
		echo " -v	Print script version"
		echo ""
		echo "[!] Due to bash limitations, You can use only one parameter at once."
		exit;
		;;
	-n)
		CHECKS=0
		echo " [!] Running without software checks"
		;;
	-v)
		echo " [i] SupTime script $VERSION"
		exit;
		;;
	-i)
		echo "[i] Information about settings:"
		echo "Temponary directory:	$TMP_DIR"
		echo "Base directory:		$BASE_DIR"
		echo "Output file location:	$OUT"
		echo "Using theme:		$THEME"
		echo "Upload protocol:		$UPLOAD"
		echo "Upload user:		$USER"
		echo "Upload host:		$HOST"
		exit;
		;;
esac

# Network connection checker
connection_check () {
	ping -c 1 google.com > /dev/null && NET=1 || NET=0
}

# Check network connection if uploading via ftp or ssh
case "$UPLOAD" in
	ftp|ssh|scp)
		echo " [i] Checking network connection"
		connection_check
		if [ "$NET" != "1" ]; then
			echo " [e] No network connection!"
			exit;
		fi
		;;
esac

# Software checks
if [ "$CHECKS" != "0" ]; then
	# Check if uprecords is installed
	if [ ! -e "$UPRECORDS_BIN" ]; then
		echo " [e] Please install uprecords program "
		exit;
	fi
	# Check if ImageMagick is installed
	IMAGEMAGICK_VER=`$IDENTIFY_BIN -version | head -n 1 | awk {'print $3'} \
	| sed 's/\.//g'`
	if [ "$IMAGEMAGICK_VER" -lt "625" ]; then
		echo " [e] Your ImageMagick version is older than 6.2.5"
		exit;
	fi
fi

# Read current uptime from uprecords
if [ "$1" == "-s" ]; then
	PID=`ps aux | grep suptimed.sh | grep "su -c" | head -n 1 | awk '{print $2}'`
	UPTIME="shutdown"
	if [ -n "$PID" ]; then
		kill $PID > /dev/null&& \
		echo " [i] Rendering shutdown image"
	else
		echo " [!] No SupTimeDaemon running found!"
		echo " [i] Rendering shutdown image"
	fi
else
	echo " [i] Rendering uptime image"
	UPTIME_DAYS=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3}'`
	case "$UPTIME_DAYS" in
		1)
			UPTIME=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3 $4 $5 $6 }' \
			| sed 's/\day/ day/' |sed 's/\,/ /'`
			;;
		*)
			UPTIME=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3 $4 $5 }' \
			| sed 's/\days/ days/' |sed 's/\,/ /'`
			;;
	esac
fi

# Read top uptime from uprecords
TOP_DAYS=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' | awk '{print $2}'`
case $TOP_DAYS in
	1)
		TOP=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' \
		| awk '{print $2 $3 $4 $5}' | sed 's/\day/ day/' |sed 's/\,/ /'`
		;;
	*)
		TOP=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' \
		| awk '{print $2 $3 $4}' | sed 's/\days/ days/' |sed 's/\,/ /'`
		;;
esac

# Load theme configuration and text layer
if [ -e $BASE_DIR/$THEME/theme.conf ]; then
	THEME_LINES=`cat $BASE_DIR/$THEME/theme.conf  |wc -l`
	if [ "$THEME_LINES" -ge 5 ]; then
		cat $BASE_DIR/$THEME/theme.conf | head -n 3 > $TMP_DIR/theme.tmp
		cat $BASE_DIR/$THEME/theme.conf | grep "#FONT#" | sed 's/\#FONT# //' \
		>> $TMP_DIR/theme.tmp
		. $TMP_DIR/theme.tmp
		LAYERS_LOADED=0
		while [ "$LAYERS_LOADED" -lt  "$LAYERS" ]; do
			LAYERS_LOADED=$[$LAYERS_LOADED+1]
			cat $BASE_DIR/$THEME/theme.conf | grep "#LAYER$LAYERS_LOADED#" \
			> $TMP_DIR/LAYER"$LAYERS_LOADED".tmp
			LAYERS_LINES=`cat $TMP_DIR/LAYER*.tmp| wc -l`
			if [ "$LAYERS_LINES" -ge 2 ]; then
				. $TMP_DIR/LAYER"$LAYERS_LOADED".tmp
			else
				echo " [e] Error in config file!"
				exit;
			fi
		done
	else
		echo " [e] Error in config file!"
		exit;
	fi
else
	echo " [e] Theme not found! Check if it really exists"
	exit;
fi

# Render image with text from text file
cat $TMP_DIR/up1.txt | $CONVERT_BIN -background transparent -pointsize $FONT_SIZE \
-fill $FONT_COLOR -font $BASE_DIR/$THEME/$FONT label:@- -append $TMP_DIR/text1.png
LAYERS_MADE=0
while [ "$LAYERS_MADE" -lt "$LAYERS" ]; do
	LAYERS_MADE=$[$LAYERS_MADE+1]
	cat $TMP_DIR/up"$LAYERS_MADE".txt | $CONVERT_BIN -background transparent \
	-pointsize $FONT_SIZE -fill $FONT_COLOR -font $BASE_DIR/$THEME/$FONT \
	label:@- -append $TMP_DIR/text"$LAYERS_MADE".png
done

# Merge graphical background, text image and foreground
cat $BASE_DIR/$THEME/theme.conf | grep "#COMPOSITE#" > $TMP_DIR/composite.tmp
. $TMP_DIR/composite.tmp

# Show size of generated image
KBYTES=`du -kh $OUT | awk {'print $1'}`
echo " [i] Rendered image size is $KBYTES"

# Cleanup
rm -f $TMP_DIR/composite* $TMP_DIR/up*.txt $TMP_DIR/text*.png $TMP_DIR/theme*.tmp \
$TMP_DIR/extra*.tmp $TMP_DIR/LAYER*.tmp

# Upload image
case "$UPLOAD" in
	ssh|scp)
		$SCP_BIN	 -P $SSH_PORT $OUT $USER@$HOST:$SSH_DIR/ && \
		echo " [i] Image uploaded via scp"
		;;
	ftp)
		$NCFTPPUT_BIN -u $USER -p $PASSWORD -P $FTP_PORT $HOST $FTP_DIR $OUT > /dev/null && \
		echo " [i] Image uploaded via ftp"
		;;
esac


# Delete image from hard disk if uploaded to remote server
case "$UPLOAD" in
	ftp|ssh|scp)
		rm -f $OUT
		;;
esac

exit;
